package com.homework.dao.impl;

import com.homework.dao.PermissionDao;
import com.homework.model.Permission;
import com.homework.model.Role;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author HLQ
 * @date 2024/9/29 11:16
 */
@Repository
@Slf4j
public class PermissionDaoImpl implements PermissionDao {

    @Autowired
    private Connection conn;
    @Autowired
    private Permission per;
    public Integer insert(Permission per){
        String sql = "INSERT INTO tb_permission" + "(permission_name,description,url)"
                + "VALUES" + "(?,?,?)" ;
        try(
                PreparedStatement ps = conn.prepareStatement(sql);
        ){
            ps.setString(1, per.getPerName());
            ps.setString(2,per.getDescription());
            ps.setString(3, per.getUrl());
            return ps.executeUpdate();
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return 0;
    };
    //test
    public Integer update(Permission per){
        String sql = "UPDATE  tb_permission SET description=?,url=? WHERE permission_name=?";
        try(
                PreparedStatement ps = conn.prepareStatement(sql);
        ){
            ps.setString(1,per.getDescription());
            ps.setString(2, per.getUrl());
            ps.setString(3, per.getPerName());
            return ps.executeUpdate();
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return 0;
    };
    public Integer delete(String perName){
        String sql = "DELETE  FROM tb_permission WHERE permission_name=?";
        try(
                PreparedStatement ps = conn.prepareStatement(sql);
        ){
            ps.setString(1,perName);
            return ps.executeUpdate();
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return 0;
    };
    public List<Permission> selectPer(String perName){
        String sql = "SELECT * FROM tb_permission WHERE permission_name=?";
        List<Permission> perList = new ArrayList<>();
        try(
                PreparedStatement ps = conn.prepareStatement(sql);
        ){
            ps.setString(1,perName);
            ResultSet rs = ps.executeQuery();
            while  (rs.next()) {
                per.setPerId(rs.getInt("permission_id"));
                per.setPerName(rs.getString("permission_name"));
                per.setDescription(rs.getString("description"));
                per.setUrl(rs.getString("url"));
                perList.add(per);
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return perList;
    }

}
